package com.leoman.spinningmachine.tab3;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.leoman.helper.util.FrescoUtil;
import com.leoman.helper.util.JsonKit;
import com.leoman.helper.util.LogUtil;
import com.leoman.helper.util.ToastUtil;
import com.leoman.spinningmachine.R;
import com.leoman.spinningmachine.base.BaseActivity;
import com.leoman.spinningmachine.bean.DayCardInfoBean;
import com.leoman.spinningmachine.constant.Constant;
import com.leoman.spinningmachine.http.APIResponse;
import com.leoman.spinningmachine.http.WebServiceApi;
import com.leoman.spinningmachine.login.LoginActivity;
import com.leoman.spinningmachine.util.DateUtil;
import com.leoman.spinningmachine.util.DialogUtils;
import com.leoman.spinningmachine.util.QuitUtil;
import com.leoman.spinningmachine.util.SharedPreferencesUtils;
import com.leoman.spinningmachine.view.CustomCalendar;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.leoman.spinningmachine.constant.Urls.HEAD_IMAGE;

/**
 * Created by Administrator on 2018-05-07.
 * 考勤打卡
 */
public class CardRecordActivity extends BaseActivity implements DatePickerDialog.OnClickListener {
    @BindView(R.id.cal)
    CustomCalendar cal;
    @BindView(R.id.tv_user_nickname)
    TextView tvUserNickName;
    @BindView(R.id.user_photo)
    SimpleDraweeView user_photo;
    @BindView(R.id.tv_date)
    TextView tv_date;

    @BindView(R.id.tv_no_card)
    TextView tv_no_card;           //没记录
    @BindView(R.id.rl_cardlist)
    LinearLayout rl_cardlist;      //有记录

    @BindView(R.id.rl_sb)
    RelativeLayout rl_sb;          //上班记录
    @BindView(R.id.rl_xb)
    RelativeLayout rl_xb;          //下班记录
    @BindView(R.id.v_xb)
    View v_xb;
    @BindView(R.id.rl_zw)
    RelativeLayout rl_zw;          //中午记录
    @BindView(R.id.v_zw)
    View v_zw;

    @BindView(R.id.tv_cardData_head)
    TextView tv_cardData_head;
    @BindView(R.id.s_tvtime)
    TextView s_tvtime; //上班打卡时间
    @BindView(R.id.s_tvaddress)
    TextView s_tvaddress;

    @BindView(R.id.z_tvtime)
    TextView z_tvtime;  //中午打卡时间
    @BindView(R.id.z_tvaddress)
    TextView z_tvaddress;

    @BindView(R.id.e_tvtime)
    TextView e_tvtime; //下班打卡时间
    @BindView(R.id.e_tvaddress)
    TextView e_tvaddress;
    @BindView(R.id.tv_right)
    TextView tvRight;

    private Map<Integer, Integer> map;//-1 无打卡 ,1 不正常 ，2 正常   用于绘制小圆点
    private Map<String, List<DayCardInfoBean>> dayMap; // 指定日期的数据
    private List<DayCardInfoBean> cardlists = new ArrayList<>();     //接收服务返回的当月数据
    private Integer currentDay;
    private Integer currentYear;
    private Integer currentMonth;

    private Integer selYear = 0;
    private Integer selMonth = 0;
    private Integer selDay = 0;
    private DatePickerDialog datePickerDialog;
    private double lat, lon;
    private int num = 0;

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.ac_card_record;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initTitle("打卡记录");
        tvRight.setText("打卡");
        tvRight.setVisibility(View.VISIBLE);

        tvUserNickName.setText("" + SharedPreferencesUtils.getInstance().getString(Constant.NICKNAME));
    }

    public void startLocaion() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //获取一次定位结果：  该方法默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    Log.i("纬度", "纬度-----------------" + amapLocation.getLatitude());//获取纬度
                    Log.i("经度", "经度-----------------" + amapLocation.getLongitude());//获取经度
                    lat = amapLocation.getLatitude();
                    lon = amapLocation.getLongitude();
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };


    @Override
    protected void initData() {
        map = new HashMap<>();
        dayMap = new HashMap<>();
        LogUtil.json("初始化数据");
        requestData(DateUtil.getTodayStr());
        FrescoUtil.setImg(this, user_photo, HEAD_IMAGE + SharedPreferencesUtils.getInstance().getString(Constant.HEADPATH));
        Date date = new Date();
        currentYear = Integer.valueOf(cal.getCurrentYear(date));
        currentMonth = Integer.valueOf(cal.getCurrentMonth(date));
        currentDay = Integer.valueOf(cal.getCurrentDay(new Date()));

        if (currentMonth < 10) {
            tv_date.setText(currentDay > 10 ? currentYear + "-0" + currentMonth + "-" + currentDay : currentYear + "-0" + currentMonth + "-0" + currentDay);
        } else {
            tv_date.setText(currentDay > 10 ? currentYear + "-" + currentMonth + "-" + currentDay : currentYear + "-" + currentMonth + "-0" + currentDay);
        }
        setListener();
        LogUtil.json(getlayTimeStr("01:20:30") + "," + getlayTimeStr("00:20:30") + "," + getlayTimeStr("00:00:40"));
    }

    /**
     * 请求
     *
     * @param date
     */
    private void requestData(String date) {
        DialogUtils.getInstance().show(this);
        String token = SharedPreferencesUtils.getInstance().getString("token");
        WebServiceApi.getInstance().getMonthRecordData(token, date, this, 1);
    }

    private void setListener() {
        cal.setOnClickListener(new CustomCalendar.onClickListener() {
            @Override
            public void onWeekClick(int weekIndex, String weekStr) {
            }

            @Override
            public void onDayClick(int day, String dayStr) {
                num = 0;
                if (selYear == 0 || selMonth == 0) {
                    if (currentMonth < 10) {
                        tv_date.setText(day < 10 ? currentYear + "-0" + currentMonth + "-0" + day : currentYear + "-0" + currentMonth + "-" + day);
                        updateList(day, day < 10 ? currentYear + "-0" + currentMonth + "-0" + day : currentYear + "-0" + currentMonth + "-" + day);
                    } else {
                        tv_date.setText(day < 10 ? currentYear + "-" + currentMonth + "-0" + day : currentYear + "-" + currentMonth + "-" + day);
                        updateList(day, day < 10 ? currentYear + "-" + currentMonth + "-0" + day : currentYear + "-" + currentMonth + "-" + day);
                    }
                } else {
                    if (selMonth < 10) {
                        tv_date.setText(day < 10 ? selYear + "-0" + selMonth + "-0" + day : selYear + "-0" + selMonth + "-" + day);
                        updateList(day, day < 10 ? selYear + "-0" + selMonth + "-0" + day : selYear + "-0" + selMonth + "-" + day);
                    } else {
                        tv_date.setText(day < 10 ? selYear + "-" + selMonth + "-0" + day : selYear + "-" + selMonth + "-" + day);
                        updateList(day, day < 10 ? selYear + "-" + selMonth + "-0" + day : selYear + "-" + selMonth + "-" + day);
                    }
                }
            }
        });
    }

    @OnClick({R.id.tv_date, R.id.tv_right})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_date:
                datePickerDialog = new DatePickerDialog(this, 0, null, currentYear, currentMonth - 1, currentDay);
                datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "确定", this);
                datePickerDialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "取消", this);
                datePickerDialog.show();
                break;
            case R.id.tv_right: //异地打卡
                startLocaion();
                if (lat != 0 && lon != 0) {
                    WebServiceApi.getInstance().yidi(String.valueOf(lon), String.valueOf(lat), this, 2);
                }
                break;
        }
    }

    @Override       //设置日期
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DatePickerDialog.BUTTON_POSITIVE:
                num = 0;
                DatePicker picker = datePickerDialog.getDatePicker();
                int year = picker.getYear();
                int month = picker.getMonth();
                int dayOfMonth = picker.getDayOfMonth();
                if (selYear == year && selMonth == month + 1 && selDay == dayOfMonth) {
                    return;
                }
                if ((month + 1) < 10) {
                    tv_date.setText(dayOfMonth < 10 ? year + "-0" + (month + 1) + "-0" + dayOfMonth : year + "-0" + (month + 1) + "-" + dayOfMonth);
                } else {
                    tv_date.setText(dayOfMonth < 10 ? year + "-" + (month + 1) + "-0" + dayOfMonth : year + "-0" + (month + 1) + "-" + dayOfMonth);
                }
                cal.setMonth(year + "年" + (month + 1) + "月", dayOfMonth + "");
                currentYear = year;
                currentMonth = month + 1;
                currentDay = dayOfMonth;
                if ((month + 1) < 10) {
                    requestData(dayOfMonth > 10 ? year + "-0" + (month + 1) + "-" + dayOfMonth : year + "-0" + (month + 1) + "-0" + dayOfMonth);
                } else {
                    requestData(dayOfMonth > 10 ? year + "-" + (month + 1) + "-" + dayOfMonth : year + "-" + (month + 1) + "-0" + dayOfMonth);
                }
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                dialog.cancel();
                break;
        }
    }

    @Override
    public void OnSuccessData(APIResponse apiResponse, Integer tag) {
        if (1 == tag) {
            if ("100".equals(apiResponse.data.code)) {
                QuitUtil.quit(true);
                gotoOtherActivity(LoginActivity.class);
                finish();
                return;
            }
            cardlists.clear();
            cardlists = apiResponse.data.list;
            LogUtil.e(JsonKit.toJson(cardlists));
            setMapData(cardlists);
            DialogUtils.getInstance().cancel();
        } else {
            Log.e("DateUtil.getTodayStr()", DateUtil.getTodayStr());
            requestData(DateUtil.getTodayStr());    //请求接口数据  重新加载
            ToastUtil.showToast(this, "打卡成功", Toast.LENGTH_SHORT);
        }
    }


    //更新打卡列表
    private void updateList(int index, String date) {
        if (map != null && map.size() > 0 && map.keySet().contains(index)) {  //有记录
            rl_cardlist.setVisibility(View.VISIBLE);
            if (dayMap != null && dayMap.size() > 0) {
                rl_sb.setVisibility(View.GONE);
                rl_zw.setVisibility(View.GONE);
                rl_xb.setVisibility(View.GONE);
                v_zw.setVisibility(View.GONE);
                v_xb.setVisibility(View.GONE);
                tv_cardData_head.setVisibility(View.GONE);

                if (dayMap.keySet().contains(date)) {
                    List<DayCardInfoBean> beans = cardlists;
                    for (DayCardInfoBean bean : beans) {
                        if (bean.getDays().equals(date)) {
                            tv_no_card.setVisibility(View.GONE);
                            tv_cardData_head.setVisibility(View.VISIBLE);
                            if (bean.getTypeName().equals("早")) {
                                rl_sb.setVisibility(View.VISIBLE);
                                setSbRecord(bean);
                                num++;
                            } else if (bean.getTypeName().equals("中")) {
                                rl_zw.setVisibility(View.VISIBLE);
                                v_zw.setVisibility(View.VISIBLE);
                                setZwRecord(bean);
                                num++;
                            } else if (bean.getTypeName().equals("晚")) {
                                rl_xb.setVisibility(View.VISIBLE);
                                v_xb.setVisibility(View.VISIBLE);
                                setXbRecord(bean);
                                num++;
                            }
                            tv_cardData_head.setText("今日打卡：" + num + "次");
                        }
                    }
                }
            }
        } else {
            tv_no_card.setVisibility(View.VISIBLE);
            rl_cardlist.setVisibility(View.GONE);
        }
    }


    /**
     * 早上打卡数据
     *
     * @param bean
     */
    private void setSbRecord(DayCardInfoBean bean) {
        if (bean != null) {
            s_tvaddress.setText(bean.getAddr());
            s_tvtime.setText("打卡时间 " + DateUtil.getyMdHms(bean.getTime(), "HH:mm"));
        }
    }

    /**
     * 中午打卡数据
     *
     * @param bean
     */
    private void setZwRecord(DayCardInfoBean bean) {
        if (bean != null) {
            z_tvaddress.setText(bean.getAddr());
            z_tvtime.setText("打卡时间" + DateUtil.getyMdHms(bean.getTime(), "HH:mm"));
        }
    }

    /**
     * 晚上打卡数据
     *
     * @param bean
     */
    private void setXbRecord(DayCardInfoBean bean) {
        if (bean != null) {
            e_tvaddress.setText("" + bean.getAddr());
            e_tvtime.setText("打卡时间 " + DateUtil.getyMdHms(bean.getTime(), "HH:mm"));
        }
    }

    /**
     * 获取迟到时间
     *
     * @param laytime
     * @return
     */
    private String getlayTimeStr(String laytime) {
        if (TextUtils.isEmpty(laytime)) {
            return "";
        }
        String[] laytimeArray = laytime.split(":");
        if (laytimeArray != null && laytimeArray.length == 3) {
            String hour = laytimeArray[0];
            String min = laytimeArray[1];
            String m = laytimeArray[2];
            if ("00".equals(hour) && "00".equals(min)) {
                return Integer.valueOf(m) + "秒";
            } else if ("00".equals(hour)) {
                return Integer.valueOf(min) + "分钟";
            } else {
                return Integer.valueOf(hour) + "小时" + Integer.valueOf(min) + "分钟";
            }
        }
        return "";
    }

    /**
     * 服务器返回的数据
     *
     * @param cardlists
     */
    private void setMapData(List<DayCardInfoBean> cardlists) {
        map.clear();
        dayMap.clear();
        if (cardlists != null && cardlists.size() > 0) {
            for (int i = 0; i < cardlists.size(); i++) {
                DayCardInfoBean bean = cardlists.get(i);
                System.out.println(i + "打卡：" + bean);
                String date = bean.getDays();//日期
                if (!dayMap.containsKey(date)) {
                    dayMap.put(date, new ArrayList<DayCardInfoBean>());
                }
                List<DayCardInfoBean> beans = dayMap.get(date);
                beans.add(bean);
            }
        }
        if (cal != null) {
            for (String index : dayMap.keySet()) {
                String[] s = index.split("-");
                if (Integer.parseInt(s[0]) == currentYear && Integer.parseInt(s[1]) == currentMonth) {
                    int size = dayMap.get(index).size();
                    int key = Integer.parseInt(s[2]);
                    if (size == 3) {
                        map.put(key, 2);
                    } else if (size > 0 && size < 3) {
                        map.put(key, 1);
                    } else {
                        map.put(key, -1);
                    }
                }
            }
            cal.setData(map);
            if (currentMonth < 10) {
                updateList(currentDay, currentDay < 10 ? currentYear + "-0" + currentMonth + "-0" + currentDay : currentYear + "-0" + currentMonth + "-" + currentDay);
            } else {
                updateList(currentDay, currentDay < 10 ? currentYear + "-" + currentMonth + "-0" + currentDay : currentYear + "-" + currentMonth + "-" + currentDay);
            }

        } else {
            LogUtil.json("cal:为空");
        }
    }
}
